package com.cqw;

import com.cqw.commontest.stream.User;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @Author: caoqingwen
 * @CreateTime: 2022-05-10 14:41
 * @Description:
 */
public class Test1111 {

    public static void main(String[] args) throws Exception {

//        String sign = sign("fca7132061514b7da38b34b4ebcf2d09","bi1d49a72392124da4");
//        System.out.println(sign);
        User user = new User();
        if (user.getAge() == 1) {

        }
    }


    public static String sign(String appSecret, String appId) throws Exception {
        StringBuilder hexStringBuilder = new StringBuilder();
        Random random = new Random(System.currentTimeMillis());
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonce = String.valueOf(Math.abs(random.nextLong()));

        String str = String.format("app_id=%s&nonce=%s&sign=sha256&timestamp=%s", appId, nonce, timestamp);
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), mac.getAlgorithm());
        mac.init(secretKey);
        byte[] bytes = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
        hexStringBuilder.setLength(0);
        for (int i = 0; i < bytes.length; ++i) {
            String hex = Integer.toHexString(0xff & bytes[i]);
            if (hex.length() == 1) {
                hexStringBuilder.append('0');
            }
            hexStringBuilder.append(hex);
        }
        String signature = hexStringBuilder.toString();
        return str + "&signature=" + signature;
    }


}
